/* divideElems.c                             (\(\
 * Jannis Teunnissen and Florian Speelman    (='.')
 * Scientific Computing - spring 2010        o(_")")
 */

#include <stdio.h>
#include <math.h>
#include <sys/time.h>

void divideElems(int *nElemsArray, int *displs, int *weights, int totalElems, int ntasks) {
    int accumWeight[ntasks], totalWeight, i;
    
    for(i = 0; i < ntasks; i++) {
        accumWeight[i] = weights[i];
        if(i > 0) {
            accumWeight[i] += accumWeight[i-1];
        }
    }
    totalWeight = accumWeight[ntasks - 1];
    
    nElemsArray[0] = (totalElems * accumWeight[0]) / totalWeight;
    for(i = 1; i < ntasks; i++) {
        nElemsArray[i] = (totalElems * accumWeight[i]) / totalWeight - (totalElems * accumWeight[i-1]) / totalWeight;
    }
    
    displs[0] = 0;
    for(i = 1; i < ntasks; i++) {
        displs[i] = nElemsArray[i-1] + displs[i-1];
    }
}

void printWeights(int *weights, int ntasks) {
    for(int i = 0; i < ntasks; i++) {
        printf("Rank %d has weight %d\n", i, weights[i]);
    }
    printf("\n");
}

int benchmark(void) {
    int i;
    double temp, res = 0.;
    struct timeval start, end;
    
    gettimeofday(&start, NULL);
    
    for(i = 1; i < 8000*1000; i++) {
        temp = 1. / (double) i;
        res += temp * temp;
        res *= sqrt(res + 1.) / sqrt(res);
    }
    
    gettimeofday(&end, NULL);
    
    temp = 1000. / (end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec) * 1.e-6);
    return (int)temp;
}
